package com.fingard.dsp.bank.directbank.chinaums01.util;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;

import com.fingard.dsp.bank.directbank.chinaums01.ChinaUMS01Base;

public class SignUtil extends ChinaUMS01Base {
    static public String buildSignString(Map<String, String> params) {
        List<String> keys = new ArrayList<String>(params.size());

        for (String key : params.keySet()) {
            if ("sign".equals(key) || "sign_type".equals(key))
                continue;
            if (StringUtils.isEmpty(params.get(key)))
                continue;
            keys.add(key);
        }

        Collections.sort(keys);

        StringBuilder buf = new StringBuilder();
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
                buf.append(key + "=" + value);
            } else {
                buf.append(key + "=" + value + "&");
            }
        }
        return buf.toString();
    }

    static public String signWithMd5(Map<String, String> params, String md5Key, String charset) throws UnsupportedEncodingException {
        String prestr = buildSignString(params); 
        return signWithMd5(prestr, md5Key, charset);
    }

    static public String signWithMd5(String originStr, String md5Key, String charset) throws UnsupportedEncodingException {
        String text = originStr + md5Key;
        return DigestUtils.md5Hex(text.getBytes("utf-8")).toUpperCase();
    }
}
